#!/usr/bin/perl

## copydir

# A helper script to make a copy of an entire directory on the local
# machine, taking arguments from environment variables and passing
# them safely to rm and cp calls.  CP_SRC and CP_DST should both be in
# UTF-8 format.  No need to run this script as uid or setuid 0.

use strict;
{
	my $exitCode = 1;
	
	my (
		$SrcPath, 
		$DstPath, 
		$Touch,
		) = 
		@ENV{qw(
				CP_SRC
				CP_DST
				TOUCH
				)};
	

	## Exercise caution on the destination path: must start with slash
	## but be at least 12 chars in length.

	if (length($DstPath)  <  12   ) {goto done;}
	if (       $DstPath   !~ m{^/}) {goto done;}

	
	## Ensure both src and dst path end with slash.
	$SrcPath =~ s{([^/])\Z}{$1/};
	$DstPath =~ s{([^/])\Z}{$1/};
	
#print "Copying:\n'$SrcPath' ==> \n'$DstPath'\n";

	if (!-e $SrcPath) {warn("Src dir not found: '$SrcPath'\n"); goto done;}
	if ( -e $DstPath) {system("rm", "-rf",       $DstPath);               }
	if ( -e $DstPath) {warn("Failed to remove   '$DstPath'\n"); goto done;}
	if (!-e $DstPath) {system("mkdir", "-p",     $DstPath);               }
	if (!-e $DstPath) {warn("Failed to create   '$DstPath'\n"); goto done;}
	if ( -e $SrcPath) {system("ditto",           $SrcPath,      $DstPath);}
	if (($?>>8) != 0) {warn("Failed to copy     '$DstPath'\n"); goto done;}
	if (!-e $DstPath) {warn("Failed to copy     '$DstPath'\n"); goto done;}
	if ( -e $DstPath) {system("touch",           $DstPath) if $Touch;     }
	if (($?>>8) != 0) {warn("Failed to touch    '$DstPath'\n");           }
	
	$exitCode = 0;	## Success
  done:
	exit($exitCode);
}
